/**
 * This implements the user login mechanism for Hollyweb.
 * @module
 */
import axios from "axios";
import { joinURL } from "../components/common/utilities.js";
import { HOST_NAME_PORT } from "../lib/constants.js";
import {
  getFromStorage,
  clearStorage,
  saveToStorage,
} from "../localCache/lilyLocalCache.js";
import { initUserCache } from "./userData.js";
import { getLawRootStorage } from "../localCache/legalContentStorage.js";


/**
 * Login user, if successful, construct loginData, groups, messages, and transfer userInfo to peopleMap
 * @param {object} userObj - { account, password }
 * @returns {string} error message if any
 */
export async function loginUser(userObj) {
  const url = joinURL(HOST_NAME_PORT, "user/login");
  try {
    const response = await axios.post(url, userObj);
    const { userInfo, accessToken, refreshToken } = response.data;
    //TODO这里最好进行封装
    saveToStorage("access_token", accessToken);
    saveToStorage("refresh_token", refreshToken);
    if (userInfo) {
      await initUserCache(userInfo);
      //初始化lawRoot
      await getLawRootStorage();
      return "";
    }
  } catch (err) {
    //do nothing
  }
  return "登录失败";
}

/**
 * Register user, if successful
 * @param {object} userObj - { nickname, account, password }
 * @returns {string} error message if any
 */
export async function registerUser(userObj) {
  const url = joinURL(HOST_NAME_PORT, "user/register");
  try {
    const response = await axios.post(url, userObj);
    const userInfo = response.data;
    if (userInfo) {
      return "";
    }
  } catch {
    // do nothing
  }
  return "注册失败";
}
/**
 * logout user, if successful
 * @param {object} userObj - { nickname, account, password }
 * @returns {string} error message if any
 */
export async function logoutUser() {
  const url = joinURL(HOST_NAME_PORT, "user/logout");
  try {
    await axios.post(url, { refreshToken: getFromStorage("refresh_token") });
  } catch (error) {
    //do nothing
  } finally {
    //清除缓存
    clearStorage();
  }
}


/**
 * Empty login data validation
 * @param {string} account
 * @param {string} password
 * @returns error message if failed validation
 */
function isEmptyLoginData(account, password) {
  let error = "";
  // Check whether fields are empty
  if (
    typeof account === "undefined" ||
    typeof password === "undefined" ||
    account.length === 0 ||
    password.length === 0
  ) {
    error = "⚠ 账号和密码不能为空。";
  }
  return error;
}
/**
 * Empty login data validation
 * @param {string} account
 * @param {string} password
 * @returns error message if failed validation
 */
function isEmptyRegisterData(nickname, account, password) {
  let error = "";
  // Check whether fields are empty
  if (
    typeof nickname === "undefined" ||
    typeof account === "undefined" ||
    typeof password === "undefined" ||
    account.length === 0 ||
    password.length === 0
  ) {
    error = "⚠ 昵称、账号和密码不能为空。";
  }
  return error;
}
/**
 * Simple password validation
 * @param {string} password
 * @returns error message if failed validation
 */
function validatePassword(password) {
  let error = "";
  // Simple validation on password
  if (
    typeof password !== "string" ||
    password.length < 8 ||
    !/[a-z]/.test(password) ||
    !/[A-Z]/.test(password) ||
    !/\d/.test(password) ||
    !/\W/.test(password)
  ) {
    error = "密码至少八位，必须包含大小写字母、数字和特殊字符";
  }
  return error;
}
/**
 * Simple account validation
 * @param {string} account
 * @returns error message if failed validation
 */
function validateAccount(account) {
  let error = "";
  // Simple validation on account
  if (
    typeof account !== "string" ||
    account.length < 9 ||
    account.length > 15 ||
    !/^[a-zA-Z0-9]+$/.test(account)
  ) {
    error = "账号长度必须大于等于9小于等于15且只能包括英文字符和数字";
  }
  return error;
}
/**
 * Simple login data validation
 * @param {string} account
 * @param {string} password
 * @returns error message if failed validation
 */
export function validateLoginData(account, password) {
  let error = isEmptyLoginData(account, password);
  // Simple validation on password
  if (error.length === 0) {
    error = validatePassword(password);
  }
  return error;
}

export function validateRegisterData(nickname, account, password) {
  let error = isEmptyRegisterData(nickname, account, password);
  if (error.length === 0) {
    error = validatePassword(password) + validateAccount(account);
  }
  return error;
}
